package com.lutzyt.delivery.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lutzyt.delivery.bean.Permission;
import com.lutzyt.delivery.mapper.PermissionDAO;
import com.lutzyt.delivery.service.PermissionMenuService;
import com.lutzyt.delivery.service.PermissionService;
import com.lutzyt.delivery.service.RolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zyt
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PermissionServiceImpl extends ActionServiceImpl<PermissionDAO, Permission> implements PermissionService {
  private static final String PERMISSION_ID = "permission_id";

  private PermissionDAO permissionDAO;
  private RolePermissionService rolePermissionService;
  private PermissionMenuService permissionMenuService;

  @Transactional(readOnly = true)
  @Override
  public Permission findById(Integer id) {
    return permissionDAO.selectById(id);
  }

  @Transactional(readOnly = true)
  @Override
  public IPage<Permission> findByPage(int pageNum, int pageSize) {
    return permissionDAO.selectPage(new Page<>(pageNum, pageSize), null);
  }

  @Override
  public void insert(Permission permission) {
    permissionDAO.insert(permission);
  }

  @Override
  public void update(Permission permission) {
    permissionDAO.updateById(permission);
  }

  @Override
  public void deleteById(Integer id) {
    if (rolePermissionService.query().eq(PERMISSION_ID, id).list().size() > 0) {
      throw new RuntimeException("该权限已经被分配，请收回后在删除");
    }
    permissionDAO.deleteById(id);
    permissionMenuService.update().eq(PERMISSION_ID, id).remove();
  }

  @Override
  public void deleteByIds(List<String> ids) {
    if (rolePermissionService.query().in(PERMISSION_ID, ids).count() > 0) {
      throw new RuntimeException("删除的权限中有被分配的权限，请收回后在删除");
    }
    permissionDAO.deleteBatchIds(ids);
    permissionMenuService.update().in(PERMISSION_ID, ids).remove();
  }

  @Autowired
  public void setPermissionDAO(PermissionDAO permissionDAO) {
    this.permissionDAO = permissionDAO;
  }

  @Autowired
  public void setRolePermissionService(RolePermissionService rolePermissionService) {
    this.rolePermissionService = rolePermissionService;
  }

  @Autowired
  public void setPermissionMenuService(PermissionMenuService permissionMenuService) {
    this.permissionMenuService = permissionMenuService;
  }
}